#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
AI智能客服界面 - 使用简单可靠的文本显示方式
"""

from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QTextEdit,
                             QLineEdit, QPushButton, QLabel, QFrame, QSplitter)
from PyQt5.QtCore import Qt, QThread, pyqtSignal, QDateTime
from PyQt5.QtGui import QFont, QTextCursor, QIcon
import requests


class AIAssistantThread(QThread):
    """AI助手查询线程"""
    response_received = pyqtSignal(str, object, str)  # answer, data, conversation_id
    error_occurred = pyqtSignal(str)

    def __init__(self, query, context="", conversation_id=""):
        super().__init__()
        self.query = query
        self.context = context
        self.conversation_id = conversation_id

    def run(self):
        try:
            response = requests.post(
                "http://127.0.0.1:8000/api/ai-assistant/query",
                json={"query": self.query, "context": self.context, "conversation_id": self.conversation_id},
                timeout=60
            )
            if response.status_code == 200:
                data = response.json()
                self.response_received.emit(data["answer"], data["data"], data.get("conversation_id", ""))
            else:
                self.error_occurred.emit(f"API请求失败: {response.status_code}")
        except Exception as e:
            self.error_occurred.emit(f"查询失败: {str(e)}")


class LLMWidget(QWidget):
    def __init__(self, is_admin=False):
        super().__init__()
        self.is_admin = is_admin  # 新增参数，区分用户和管理员
        self.setWindowIcon(QIcon('./images/购物.png'))
        self.conversation_history = []
        self.current_conversation_id = ""
        self.init_ui()

    def init_ui(self):
        """初始化用户界面"""
        layout = QVBoxLayout()
        layout.setContentsMargins(20, 20, 20, 20)
        layout.setSpacing(20)

        # 标题
        title = QLabel("🤖 AI客服")
        title.setFont(QFont("Microsoft YaHei", 20, QFont.Bold))
        title.setAlignment(Qt.AlignCenter)
        title.setStyleSheet("""
            QLabel {
                color: white;
                padding: 10px;
                background-color: #ff5f00;
                border-radius: 8px;
            }
        """)
        layout.addWidget(title)

        # 创建分割器
        splitter = QSplitter(Qt.Horizontal)

        # 左侧：对话区域
        self.create_chat_area(splitter)

        # 右侧：功能区域
        self.create_function_area(splitter)

        # 设置分割器比例
        splitter.setSizes([700, 200])
        splitter.setStyleSheet("QSplitter::handle { background-color: #ddd; width: 2px; }")
        layout.addWidget(splitter)

        self.setLayout(layout)
        self.setStyleSheet("QWidget { background-color: #f8f9fa; }")

    def create_chat_area(self, parent):
        """创建对话区域"""
        chat_frame = QFrame()
        chat_layout = QVBoxLayout()

        # 对话历史显示区域
        self.chat_display = QTextEdit()
        self.chat_display.setReadOnly(True)
        self.chat_display.setMinimumHeight(400)
        self.chat_display.setStyleSheet("""
            QTextEdit {
                background-color: white;
                border: 2px solid #ddd;
                border-radius: 10px;
                padding: 15px;
                font-family: Microsoft YaHei;
                font-size: 18px;
                line-height: 1.6;
            }
        """)

        # 添加欢迎消息
        welcome_message = "🤖 欢迎使用AI智能客服助手！我可以帮助您了解销售、库存、产品等信息。请告诉我您想了解什么？" if not self.is_admin else "🤖 欢迎使用AI智能客服助手！我可以帮助您了解销售、库存、产品、客户等信息。请告诉我您想了解什么？"
        self.add_message("AI助手", welcome_message, "ai")
        chat_layout.addWidget(self.chat_display)

        # 输入区域
        input_layout = QHBoxLayout()
        input_layout.setContentsMargins(5, 5, 5, 5)

        self.query_input = QLineEdit()
        self.query_input.setPlaceholderText("请输入您的问题...")
        self.query_input.setStyleSheet("""
            QLineEdit {
                border: 2px solid #ff5f00;
                border-radius: 10px;
                padding: 10px 15px;
                font-size: 18px;
                background-color: white;
                font-family: Microsoft YaHei;
            }
            QLineEdit:focus {
                border-color: #e65b00;
            }
        """)
        self.query_input.returnPressed.connect(self.send_query)
        input_layout.addWidget(self.query_input)

        self.send_button = QPushButton("发送")
        self.send_button.setStyleSheet("""
            QPushButton {
                background-color: #ff5f00;
                color: white;
                border: none;
                padding: 10px 20px;
                border-radius: 5px;
                font-size: 14px;
                font-weight: bold;
                font-family: Microsoft YaHei;
            }
            QPushButton:hover {
                background-color: #e65b00;
            }
        """)
        self.send_button.clicked.connect(self.send_query)
        input_layout.addWidget(self.send_button)

        chat_layout.addLayout(input_layout)
        chat_frame.setLayout(chat_layout)
        parent.addWidget(chat_frame)

    def create_function_area(self, parent):
        """创建功能区域"""
        function_frame = QFrame()
        function_layout = QVBoxLayout()
        function_layout.setSpacing(10)

        function_title = QLabel("快速查询")
        function_title.setStyleSheet("""
            QLabel {
                font-family: Microsoft YaHei;
                font-size: 16px;
                font-weight: bold;
                color: #333;
                margin-bottom: 10px;
            }
        """)
        function_layout.addWidget(function_title)

        # 快速查询按钮，根据 is_admin 控制客户信息按钮
        quick_queries = [
            ("📊 销售情况", "请告诉我当前的销售情况"),
            ("📦 库存情况", "请查询库存情况"),
            ("🛍️ 产品信息", "请显示产品信息概览"),
            ("🏷️ 分类信息", "请显示商品分类信息"),
            ("📈 统计汇总", "请提供系统统计汇总")
        ]
        if self.is_admin:
            quick_queries.insert(3, ("👥 客户信息", "请查询客户信息"))

        for label, query in quick_queries:
            btn = QPushButton(label)
            btn.clicked.connect(lambda checked, q=query: self.quick_query(q))
            btn.setStyleSheet("""
                QPushButton {
                    background-color: white;
                    color: #ff5f00;
                    border: 1px solid #ddd;
                    padding: 10px 15px;
                    border-radius: 5px;
                    font-size: 14px;
                    font-family: Microsoft YaHei;
                    text-align: left;
                }
                QPushButton:hover {
                    background-color: #ffe5cc;
                }
                QPushButton:pressed {
                    background-color: #ffcc99;
                }
            """)
            function_layout.addWidget(btn)

        function_layout.addStretch()
        function_frame.setLayout(function_layout)
        parent.addWidget(function_frame)

    def add_message(self, sender, message, msg_type="user"):
        """添加消息到对话区域 - 使用简单的HTML格式"""
        timestamp = QDateTime.currentDateTime().toString("HH:mm:ss")

        # 根据消息类型设置样式
        if msg_type == "user":
            style = """
                <div style="margin: 15px 0; text-align: right;">
                    <div style="display: inline-block; max-width: 70%; text-align: left;">
                        <div style="background-color: #ff5f00; color: white; padding: 12px 16px; border-radius: 18px; font-size: 18px; line-height: 1.5; word-wrap: break-word;">
                            {message}
                        </div>
                        <div style="color: #7f8c8d; font-size: 14px; margin-top: 5px; text-align: right;">
                            {timestamp}
                        </div>
                    </div>
                </div>
            """
        else:
            style = """
                <div style="margin: 15px 0; text-align: left;">
                    <div style="display: inline-block; max-width: 70%;">
                        <div style="background-color: white; color: #333; padding: 12px 16px; border-radius: 18px; font-size: 18px; line-height: 1.5; word-wrap: break-word; border: 1px solid #ddd;">
                            {message}
                        </div>
                        <div style="color: #7f8c8d; font-size: 14px; margin-top: 5px;">
                            {timestamp}
                        </div>
                    </div>
                </div>
            """

        html_message = style.format(message=message, timestamp=timestamp)
        self.conversation_history.append({
            "sender": sender,
            "message": message,
            "type": msg_type,
            "timestamp": timestamp
        })
        self.chat_display.append(html_message)
        cursor = self.chat_display.textCursor()
        cursor.movePosition(cursor.End)
        self.chat_display.setTextCursor(cursor)

    def send_query(self):
        """发送查询"""
        query = self.query_input.text().strip()
        if not query:
            return
        self.add_message("用户", query, "user")
        self.query_input.clear()
        self.send_button.setEnabled(False)
        self.send_button.setText("查询中...")
        self.query_thread = AIAssistantThread(query, context=f"is_admin={self.is_admin}", conversation_id=self.current_conversation_id)
        self.query_thread.response_received.connect(self.handle_response)
        self.query_thread.error_occurred.connect(self.handle_error)
        self.query_thread.start()

    def quick_query(self, query):
        """快速查询"""
        self.query_input.setText(query)
        self.send_query()

    def handle_response(self, answer, data, conversation_id):
        """处理查询响应"""
        self.send_button.setEnabled(True)
        self.send_button.setText("发送")
        if conversation_id:
            self.current_conversation_id = conversation_id
        self.add_message("AI助手", answer, "ai")
        if data:
            try:
                if isinstance(data, (dict, list)):
                    print(f"收到数据: {data}")
                else:
                    print(f"收到数据类型: {type(data)}, 内容: {data}")
            except Exception as e:
                print(f"处理数据时出错: {e}")

    def handle_error(self, error_message):
        """处理错误"""
        self.send_button.setEnabled(True)
        self.send_button.setText("发送")
        self.add_message("AI助手", f"❌ 查询失败：{error_message}", "ai")